//DataLoader for spreadsheet under GNU general public liscence



/*@ auther lanchana
 * DataDisplayForm.java
 *
 * Created on Nov 4, 2010, 9:54:28 PM
 * @DataLoader to the spreadsheet
 * @email:lanch.gunawardhana@gmail.com
 */

package org.openoffice;

import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.lib.uno.helper.Factory;
import com.sun.star.lang.XSingleComponentFactory;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.lib.uno.helper.WeakBase;
import com.sun.star.sheet.XCellAddressable;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheetView;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.CellAddress;
import com.sun.star.table.XCell;
import com.sun.star.table.XCellRange;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import forms.StartingFrame;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class DBForm extends WeakBase
   implements com.sun.star.lang.XInitialization,
              com.sun.star.frame.XDispatch,
              com.sun.star.lang.XServiceInfo,
              com.sun.star.frame.XDispatchProvider
{
    private final XComponentContext m_xContext;
    private com.sun.star.frame.XFrame m_xFrame;
    private static final String m_implementationName = DBForm.class.getName();
    private  DBForm addon3;
    private static final String[] m_serviceNames = {
        "com.sun.star.frame.ProtocolHandler" };


    public DBForm( XComponentContext context )
    {
        m_xContext = context;
        addon3=this;
    };

    public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
        XSingleComponentFactory xFactory = null;

        if ( sImplementationName.equals( m_implementationName ) )
            xFactory = Factory.createComponentFactory(DBForm.class, m_serviceNames);
        return xFactory;
    }

    public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) {
        return Factory.writeRegistryServiceInfo(m_implementationName,
                                                m_serviceNames,
                                                xRegistryKey);
    }

    // com.sun.star.lang.XInitialization:
    public void initialize( Object[] object )
        throws com.sun.star.uno.Exception
    {
        if ( object.length > 0 )
        {
            m_xFrame = (com.sun.star.frame.XFrame)UnoRuntime.queryInterface(
                com.sun.star.frame.XFrame.class, object[0]);
        }
    }

    // com.sun.star.frame.XDispatch:
     public void dispatch( com.sun.star.util.URL aURL,
                           com.sun.star.beans.PropertyValue[] aArguments )
    {
         if ( aURL.Protocol.compareTo("org.openoffice.dbform:") == 0 )
        {
            if ( aURL.Path.compareTo("Database") == 0 )
            {
                // add your own code here
                StartingFrame sframe=new StartingFrame(addon3);
                sframe.setVisible(true);
                //return;
            }
        }
    }
     //the function below is to get the current component's spreadsheet object by using the service manager.
     //It will allocate the cell position and populate data returned from data display form
      public void dowork(Object [][]o)//implemented by chathuri gunawardhana
             {
              XMultiComponentFactory xServiceManager = m_xContext.getServiceManager();

                try {
                    Object desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext);
                    XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);
                    XComponent xCurrentComponent = xDesktop.getCurrentComponent();
                    XSpreadsheetDocument doc=getXSpreadsheetDocument(xCurrentComponent);
                    XSpreadsheet sheet=getXSpreadsheet(doc, "Sheet1");
                    sheet=getXActiveSpreadsheet(xCurrentComponent,sheet);//get current working spreadsheet


                    XModel xDocModel = (XModel)UnoRuntime.queryInterface(XModel.class, xCurrentComponent );

       //getting the current cell position
                    XCellAddressable xSheetCellAddressable = (XCellAddressable) UnoRuntime.queryInterface(XCellAddressable.class,  xDocModel.getCurrentSelection());

                    CellAddress cellActive = xSheetCellAddressable.getCellAddress();

        //add data to the array begining with the current cell address
        for(int i=0;i<o.length;i++){
        for(int j=0;j<o[0].length;j++){

            XCell xCell = getXCellByPosition(sheet, cellActive.Column+j, cellActive.Row+i);
            XText xText = (com.sun.star.text.XText)UnoRuntime.queryInterface(com.sun.star.text.XText.class, xCell);
            XTextCursor xTextCursor = xText.createTextCursor();
            xText.insertString(xTextCursor,o[i][j].toString(), false);}
                             }
                } catch (Exception ex) {
                    Logger.getLogger(DBForm.class.getName()).log(Level.SEVERE, null, ex);
                }

    }
 public XComponent getSpreadsheetComponent(Object desktop, String templateURL) throws Exception {//getting the current spreadsheet component

        XComponentLoader xComponentLoader = (XComponentLoader)UnoRuntime.queryInterface(XComponentLoader.class, desktop);

        PropertyValue[] pPropValues;
        pPropValues = new PropertyValue[0];

        return xComponentLoader.loadComponentFromURL(templateURL, "_blank", 0, pPropValues);

    }
     //to get the current spreadsheet document
    public XSpreadsheetDocument getXSpreadsheetDocument(XComponent xSpreadsheetComponent) throws Exception {

        return(XSpreadsheetDocument)UnoRuntime.queryInterface(XSpreadsheetDocument.class, xSpreadsheetComponent);

    }
         //getting current spreadsheets
    public XSpreadsheet getXSpreadsheet(XSpreadsheetDocument xSpreadsheetDocument, String name) throws Exception {
        XSpreadsheets xSpreadsheets = xSpreadsheetDocument.getSheets();//get the sheets of the document
        Object sheet = xSpreadsheets.getByName(name);     
        return (XSpreadsheet)UnoRuntime.queryInterface(XSpreadsheet.class, sheet);
    }
        //get the currently active spreadsheet
    public XSpreadsheet getXActiveSpreadsheet(XComponent xSpreadsheetComponent, XSpreadsheet xSpreadsheet) throws Exception {
        XModel xSpreadsheetModel = (XModel)UnoRuntime.queryInterface(XModel.class, xSpreadsheetComponent);
        XController xSpreadsheetController = xSpreadsheetModel.getCurrentController();
        XSpreadsheetView xSpreadsheetView = (XSpreadsheetView)UnoRuntime.queryInterface(XSpreadsheetView.class, xSpreadsheetController);
        xSpreadsheetView.setActiveSheet(xSpreadsheet);
        return xSpreadsheet;
    }

    public XCell getXCellByPosition(XSpreadsheet xSpreadsheet, int x, int y) throws Exception {

        return xSpreadsheet.getCellByPosition(x, y);
    }
      
    public void addStatusListener( com.sun.star.frame.XStatusListener xControl,
                                    com.sun.star.util.URL aURL )
    {
        // add your own code here
    }

    public void removeStatusListener( com.sun.star.frame.XStatusListener xControl,
                                       com.sun.star.util.URL aURL )
    {
        // add your own code here
    }

    // com.sun.star.lang.XServiceInfo:
    public String getImplementationName() {
         return m_implementationName;
    }

    public boolean supportsService( String sService ) {
        int len = m_serviceNames.length;

        for( int i=0; i < len; i++) {
            if (sService.equals(m_serviceNames[i]))
                return true;
        }
        return false;
    }

    public String[] getSupportedServiceNames() {
        return m_serviceNames;
    }

    // com.sun.star.frame.XDispatchProvider:
    public com.sun.star.frame.XDispatch queryDispatch( com.sun.star.util.URL aURL,
                                                       String sTargetFrameName,
                                                       int iSearchFlags )
    {
        if ( aURL.Protocol.compareTo("org.openoffice.dbform:") == 0 )
        {
            if ( aURL.Path.compareTo("Database") == 0 )
                return this;
        }
        return null;
    }

    // com.sun.star.frame.XDispatchProvider:
    public com.sun.star.frame.XDispatch[] queryDispatches(
         com.sun.star.frame.DispatchDescriptor[] seqDescriptors )
    {
        int nCount = seqDescriptors.length;
        com.sun.star.frame.XDispatch[] seqDispatcher =
            new com.sun.star.frame.XDispatch[seqDescriptors.length];

        for( int i=0; i < nCount; ++i )
        {
            seqDispatcher[i] = queryDispatch(seqDescriptors[i].FeatureURL,
                                             seqDescriptors[i].FrameName,
                                             seqDescriptors[i].SearchFlags );
        }
        return seqDispatcher;
    }

}
